package main

import (
	"encoding/json"
	"github.com/thinkboy/log4go"
	"github.com/zhouhui8915/go-socket.io-client"
	"log"
	"os"
	"os/signal"
	"syscall"
	//"time"
)

type DataArry []string

type SubCode struct {
	Code     string `json:"code"`
	CodeName string `json:"codeName"`
	Msg      string `json:"message"`
	Content  string `json:"content"`
}

func main() {
	go ConnSocketIo()

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
	for {
		s := <-c
		switch s {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
			break
		case syscall.SIGHUP:
			break
		default:
			break
		}
	}
	log.Println("........................................................................................................................")
	return
}

func ConnSocketIo() {
	opts := &socketio_client.Options{
		//Transport: "polling",
		Transport: "websocket",
		Query:     make(map[string]string),
	}

	opts.Query["SessionId"] = "13585642792"
	client, err := socketio_client.NewClient("http://localhost:9092", opts)
	if err != nil {
		log4go.Info("SocketIo NewClient error:%v\n", err)
		return
	}

	client.On("connection", func() {
		log4go.Info("SocketIo connect\n")
	})

	err = client.On("msg", OnMsg)
	if err != nil {
		log.Panicln("on msg error:", err.Error())
	}

	err = client.On("verify", func(res string) {
		log.Println("verify: ", res)
		if res == "0" {
			log.Println("verify failed.")
		} else {
			// 发送json数据
			param := make(map[string]string)
			param["sender_acc"] = "13585642791"
			param["recver_acc"] = "13585642792"
			param["src_id"] = "1"
			param["content"] = "直播内容"
			json_byte, err := json.Marshal(param)
			if err != nil {
				log4go.Error("构造json数据失败:", err.Error(), "\n")
				return
			}
			err = client.Emit("msg", string(json_byte))
			if err != nil {
				log4go.Error("emit msg\n")
				return
			}
		}
	})
	if err != nil {
		log.Panicln("on verify error:", err.Error())
	}

	client.On("error", func() {
		log4go.Error("SocketIo error")
	})

	client.On("disconnection", func() {
		log4go.Error("SocketIo disconnect\n")
	})

	client.Emit("verify", "111111")

	//time.Sleep(time.Second * 5)
	return
}

func OnMsg(msg string) {
	log.Println("msg: ", msg)
	return
}
